package com.xdf.xzymanagementsystem.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xdf.xzymanagementsystem.dao.*;
import com.xdf.xzymanagementsystem.entity.*;
import com.xdf.xzymanagementsystem.service.ProductMainService;
import com.xdf.xzymanagementsystem.util.CodeGenUtil;
import com.xdf.xzymanagementsystem.util.SystemUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @Description : 服务层实现类，由代码生成器自动生成
 * @Author : chanchaw
 * @Date : 2025-3-21 18:43:41
 */
@Slf4j
@Service
public class ProductMainServiceImpl extends ServiceImpl<ProductMainMapper, ProductMain> implements ProductMainService {
    @Autowired
    private ProductMainMapper dao;
    @Autowired
    private ProductDetailMapper productDetailMapper;
    @Autowired
    private SystemUtils systemUtils;
    @Autowired
    private CodeGenUtil codeGenUtil;
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private HalfDetailMapper halfDetailMapper;
    //=================以上是自动生成的代码，自定义代码请写在下面==================
    @Override
    public List<Map<String, Object>> selectAllDTO(Date sdate, Date edate, int flag) {
        return dao.selectAllDTO(sdate, edate, flag);
    }

    //新增单据
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductMainDTO insertDTO(ProductMainDTO record) throws Exception {
//        if (selectRepeatOrderNo(record.getOrderNo()) != null) throw new RuntimeException("订单号已存在,不允许重复！！");
        ProductMain productMain = new ProductMain();
        BeanUtils.copyProperties(record, productMain);
        productMain.setCreateUser(systemUtils.getLoginUsername());
        productMain.setState(1);
        productMain.setBillCode(getBillCode());
        dao.insertSelective(productMain);//新增主表数据
        List<ProductDetail> detailList = record.getDetailList();
        for (ProductDetail productDetail : detailList) {
            productDetail.setParentId(productMain.getId());//关联主表id
            productDetail.setState(1);
            productDetail.setCreateUser(systemUtils.getLoginUsername());
            productDetailMapper.insertSelective(productDetail);
        }
        //获取数据并返回
        ProductMainDTO productMainDTO = selectDTO(productMain.getId());
        return productMainDTO;
    }

    //检测订单号是否重复
    private ProductMain selectRepeatOrderNo(String orderNo) {
        return dao.selectRepeatOrderNo(orderNo);
    }

    //生成单据编号
    private String getBillCode() {
        ProductMain productMain = dao.selectMaxBillCode();
        int year = LocalDate.now().getYear();
        int monthValue = LocalDate.now().getMonthValue();
        int day = LocalDate.now().getDayOfMonth();
        if (productMain != null) {
            String billCode = productMain.getBillCode();
            int codeNumber = Integer.parseInt(billCode.substring(8));
            int dayNumber = Integer.parseInt(billCode.substring(6, 8));
            if (dayNumber != day) {
                codeNumber = 0;
            }
            return "CP" + String.valueOf(year).substring(2) + String.format("%02d", monthValue) + String.format("%02d", day)  + String.format("%03d", codeNumber + 1);
        }else {
            return "CP" + String.valueOf(year).substring(2) + String.format("%02d", monthValue) + String.format("%02d", day)  + String.format("%03d", 1);
        }
    }

    @Override
    public ProductMainDTO selectDTO(Integer id) {
        ProductMainDTO productMainDTO = new ProductMainDTO();
        ProductMain main = dao.selectById(id);//查询主表
        List<ProductDetail> details = productDetailMapper.selectByParentId(id);
        BeanUtils.copyProperties(main, productMainDTO);
        productMainDTO.setDetailList(details);
        return productMainDTO;
    }

    //修改单据
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductMainDTO updateDTO(ProductMainDTO record) {
//        GreyMain main = selectRepeatOrderNo(record.getOrderNo());
        //订单号相同，id不同
//        if (main != null) {
//            if (main.getOrderNo().equals(record.getOrderNo()) && !main.getId().equals(record.getId())) throw new RuntimeException("订单号已存在,不允许重复！！");
//        }
        List<ProductDetail> detailList = record.getDetailList();
        //检测修改的匹数、公斤、米数，是否超出库存
        if (detailList.size() > 0) {
            for (ProductDetail productDetail : detailList) {
                if (productDetail.getInventoryId() != null) {
                    HalfDetail halfDetail = halfDetailMapper.selectOneById(productDetail.getInventoryId());
                    if (halfDetail.getKilo().compareTo(productDetail.getKilo()) < 0 ||
                            halfDetail.getMeter().compareTo(productDetail.getMeter()) < 0 ||
                            halfDetail.getPiece().compareTo(productDetail.getPiece()) < 0) throw new RuntimeException("输入的匹数、公斤或米数超出库存，请检查！！");
                }
            }
        }

        ProductMain productMain = new ProductMain();
        BeanUtils.copyProperties(record, productMain);
        productMain.setUpdateTime(new Date());
        productMain.setUpdateUser(systemUtils.getLoginUsername());
        if (dao.update(productMain) < 0) throw new RuntimeException("修改主表时发生错误！");
        for (ProductDetail productDetail : detailList) {
            if (Optional.ofNullable(productDetail.getId()).orElse(0) == 0) {
                productDetail.setParentId(productMain.getId());//关联主表id
                productDetail.setState(1);
                productDetail.setCreateUser(systemUtils.getLoginUsername());
                productDetailMapper.insertSelective(productDetail);
            }
            productDetail.setUpdateTime(new Date());
            productDetail.setUpdateUser(systemUtils.getLoginUsername());
            if (productDetailMapper.update(productDetail) < 0) throw new RuntimeException("修改明细时发生错误！");
        }
        List<ProductDetail> details = productDetailMapper.selectByParentId(record.getId());
        //删除掉删除行的明细
        List<ProductDetail> extraDetails = getDeleteDetails(detailList, details);
        if (extraDetails.size() > 0) {
            for (ProductDetail extraDetail : extraDetails) {
                extraDetail.setIsDelete(1);
                extraDetail.setUpdateUser(systemUtils.getLoginUsername());
                extraDetail.setUpdateTime(new Date());
                productDetailMapper.update(extraDetail);
            }
        }
        return selectDTO(record.getId());
    }

    //查询过滤删除行的明细
    private static List<ProductDetail> getDeleteDetails(List<ProductDetail> detailList, List<ProductDetail> details) {
        // 提取detailList中所有元素的ID集合
        Set<Integer> detailIds = detailList.stream()
                .map(ProductDetail::getId)
                .collect(Collectors.toSet());
        // 过滤出details中ID不在detailIds的元素
        List<ProductDetail> extraDetails = details.stream()
                .filter(d -> !detailIds.contains(d.getId()))
                .collect(Collectors.toList());
        return extraDetails;
    }

    //批量删除
    @Override
    public void deleteByIds(List<Integer> ids) {
        for (Integer id : ids) {
            ProductMain productMain = dao.selectById(id);
            OrderMain orderMain = orderMainMapper.selectRepeatOrderNo(productMain.getOrderNo());
            if (orderMain.getState() == 2) throw new RuntimeException("该订单已完成，不允许删除！！");
            List<ProductDetail> details = productDetailMapper.selectByParentId(id);
            if (details.size() > 0) {
                for (ProductDetail detail : details) {
                    detail.setIsDelete(1);
                    detail.setUpdateUser(systemUtils.getLoginUsername());
                    detail.setUpdateTime(new Date());
                    productDetailMapper.update(detail);
                }
            }
            productMain.setIsDelete(1);
            productMain.setUpdateUser(systemUtils.getLoginUsername());
            productMain.setUpdateTime(new Date());
            dao.update(productMain);
        }
    }

    @Override
    public List<Map<String, Object>> selectInventory(String orderNo) {
        List<Map<String, Object>> list = dao.selectInventory(orderNo);
        if (orderNo != null) {
            OrderMain orderMain = orderMainMapper.selectRepeatOrderNo(orderNo);
            List<OrderDetail> details = orderDetailMapper.selectByParentId(orderMain.getId());
            //通过品名、规格、颜色将订单单价填充至成品库存对应明细
            details.forEach(detail ->
                    list.stream()
                            .filter(map ->
                                    Objects.equals(detail.getProductName(), map.get("productName")) &&
                                            Objects.equals(detail.getProductSpecification(), map.get("productSpecification")) &&
                                            Objects.equals(detail.getColor(), map.get("color")))
                            .forEach(new Consumer<Map<String, Object>>() {
                                @Override
                                public void accept(Map<String, Object> matchedMap) {
                                    matchedMap.put("price", detail.getPrice());
                                    matchedMap.put("priceUnit", detail.getPriceUnit());
                                }
                            }) // 遍历所有匹配项
            );
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> selectAllInventory() {
        return dao.selectAllInventory();
    }
}